<?php

header("Content-type: text/html; charset=utf-8");
include_once('Logging.php');

class UUExpressClass{
    # 测试环境
    const APPID = 'ccba8bd4a2d54a2fb6df97e87979f303';
    const APPKEY = '2815a7a1f8e3405d81fd6263683ec4e7';
    const OPENID = '910a0dfd12bb4bc0acec147bcb1ae246';

    # 生产环境【测试】
//    const APPID = '9cbe4963c7b447eab0422780c09e6f71';
//    const APPKEY = 'e2d4699479244720b52c2eef86bd234f';
//    const OPENID = '4da1c22b3c6c4021a851d3713f2d54f9';
//    const BILL_URL_TEST = 'https://openapi.uupt.com/v2_0/';

    const BILL_URL_TEST = 'http://openapi.test.uupt.com/v2_0/';
    const BILL_URL = 'https://openapi.uupt.com/v2_0/';

    private $AppID = '';
    private $AppKey = '';
    private $OpenID = '';
    public function __construct($isDebug,$AppID,$AppKey,$OpenID){
        $this->isDebug = $isDebug;
        $this->AppID = $AppID;
        $this->AppKey = $AppKey;
        $this->OpenID = $OpenID;
    }


    /** 计价
     * @param $data
     */
    public function getorderprice($data){
        $AppID = (($this->isDebug) ? self::APPID : ($this->AppID));
        $AppKey = (($this->isDebug) ? self::APPKEY : ($this->AppKey));
        $OpenID = (($this->isDebug) ? self::OPENID : ($this->OpenID));
        $url = (($this->isDebug) ? self::BILL_URL_TEST : (self::BILL_URL)).'getorderprice.ashx';
        $guid = str_replace('-', '', $this->guid());
        $parameter = [
            'appid' => $AppID,
            'openid' => $OpenID,
//            'shop_id' => 100046,
            'timestamp' => time(),
            'nonce_str' => strtolower($guid),
            'from_lng' => $data['deliver_lng'],                                                         # 起始地坐标经度
            'from_lat' => $data['deliver_lat'],                                                         # 起始地坐标纬度
            'to_lng' => $data['to_lng'],                                                                # 收货地坐标纬度
            'to_lat' => $data['to_lat'],                                                                # 收货地坐标纬度
            'send_type' => 0,                                                                           # 订单小类 0帮我送(默认) 1帮我买
            'city_name' => $data['deliver_city'],                                                       # 订单所在城市名 称(如郑州市就填”郑州市“，必须带上“市”)
            'to_address' => $data['receiver_address'],                                                  # 目的地址
            'from_address' => $data['deliver_province'].$data['deliver_city'].$data['deliver_area'].$data['deliver_address'],  # 起始地址
            'origin_id' => $data['shop_express_no'],                                                    # 第三方对接平台订单id
        ];
        $baiduBS = new BaiduLBS();
        $baiduBSInfo = $baiduBS::switchLocation($parameter['to_lng'],$parameter['to_lat']);

        # 收货经纬度转百度
        $location = json_decode($baiduBSInfo,true);
        $parameter['to_lng'] = $location['result'][0]['x'];
        $parameter['to_lat'] = $location['result'][0]['y'];


        # 发送经纬度转百度
//        $baiduBSInfo_from= $baiduBS::switchLocation($parameter['from_lng'],$parameter['from_lat']);
//        $location_from = json_decode($baiduBSInfo_from,true);
//        $parameter['from_lng'] = $location_from['result'][0]['x'];
//        $parameter['from_lat'] = $location_from['result'][0]['y'];
        ksort($parameter);


//        echo '<pre>';
//        var_dump($parameter);die;

        $parameter['sign'] = $this->sign($parameter, $AppKey);
        $result = $this->request_post($url, $parameter);
        $result = json_decode($result, true);
        return $result;
    }

    /** 推送订单
     * @param $data
     */
    public function addorder($data){
        $AppID = (($this->isDebug) ? self::APPID : ($this->AppID));
        $AppKey = (($this->isDebug) ? self::APPKEY : ($this->AppKey));
        $OpenID = (($this->isDebug) ? self::OPENID : ($this->OpenID));
        $url = (($this->isDebug) ? self::BILL_URL_TEST : (self::BILL_URL)).'addorder.ashx';
        $guid = str_replace('-', '', $this->guid());
        $parameter = [
            'price_token' => $data['price_token'],                                                                  # 金额令牌，计算订单价格接口返回的price_token
            'order_price' => $data['total_money'],                                                                  # 订单金额，计算订单价格接口返回的total_money
            'balance_paymoney' => $data['balance_paymoney'],                                                        # 实际余额支付金额计算订单价格接口返回的need_paymoney
            'receiver' => $data['receiver'],
            'receiver_phone' => $data['receiver_tel'],
            'callback_url' =>  $data['callbackUrl'].'/service/service/UUCallBack',                                  # 订单提交成功后及状态变化的回调地址
            'push_type' =>  (($this->isDebug) ? 2: 0),                                                              # 推送方式（0 开放订单，2测试订单）默认传0即可
            'special_type' =>  (($this->isDebug) ? 0: 1),                                                           # 特殊处理类型，是否需要保温箱 1需要 0不需要
            'callme_withtake' =>  0,                                                                                # 取件是否给我打电话 1需要 0不需要
            'pubusermobile' =>  $data['deliver_phone'],                                                             # 发件人电话，（如果为空则是用户注册的手机号）
            'pay_type' =>  1,                                                                                       # 支付方式：1=企业支付 0账户余额支付（企业余额不足自动转账户余额支付）
            'appid' => $AppID,
            'openid' => $OpenID,
            'timestamp' => time(),
            'nonce_str' => strtolower($guid),
        ];

        if(!empty($data['shop_express_remark']))
            $parameter['note'] = $data['shop_express_remark'];

        ksort($parameter);
        $parameter['sign'] = $this->sign($parameter, $AppKey);
        $result = $this->request_post($url, $parameter);
        $result = json_decode($result, true);
        return $result;
    }


    /**
     * 取消订单
     * @return string
     * @param $post 数组参数 CANCEL_TEST
     */
    public function cancelorder($data){
        $AppID = (($this->isDebug) ? self::APPID : ($this->AppID));
        $AppKey = (($this->isDebug) ? self::APPKEY : ($this->AppKey));
        $OpenID = (($this->isDebug) ? self::OPENID : ($this->OpenID));
        $url = (($this->isDebug) ? self::BILL_URL_TEST : (self::BILL_URL)).'cancelorder.ashx';
        $guid = str_replace('-', '', $this->guid());
        $parameter = [
//            'order_code' => $data['order_code'],                # UU跑腿订单编号，order_code和origin_id必须二选其一，如果都传，则只根据order_code返回
            'origin_id' => $data['origin_id'],                      # 第三方对接平台订单id，order_code和origin_id必须二选其一，如果都传，则只根据order_code返回
            'reason' => $data['reason'],                          # 取消原因
            'openid' => $OpenID,
            'appid' => $AppID,
            'timestamp' => time(),
            'nonce_str' => strtolower($guid),
        ];
        ksort($parameter);

//        echo '<pre>';
//        var_dump($parameter);die;
        $parameter['sign'] = $this->sign($parameter, $AppKey);

        $result = $this->request_post($url, $parameter);
        if (!empty($result)){
            $result = json_decode($result, true);
        }
        return $result;
    }

    /**
     * 获取店铺列表
     * @return string
     * @param $post 数组参数 CANCEL_TEST
     */
    public function getshoplist(){
        $AppID = (($this->isDebug) ? self::APPID : ($this->AppID));
        $AppKey = (($this->isDebug) ? self::APPKEY : ($this->AppKey));
        $OpenID = (($this->isDebug) ? self::OPENID : ($this->OpenID));
        $url = (($this->isDebug) ? self::BILL_URL_TEST : (self::BILL_URL)).'getshoplist.ashx';
        $guid = str_replace('-', '', $this->guid());
        $parameter = [
            'pageindex' => 1,
            'sign' => '上海市',
            'openid' => $OpenID,
            'appid' => $AppID,
            'timestamp' => time(),
            'nonce_str' => strtolower($guid),
        ];
        ksort($parameter);
        $parameter['sign'] = $this->sign($parameter, $AppKey);
        $result = $this->request_post($url, $parameter);
        if (!empty($result)){
            $result = json_decode($result, true);
            echo '<pre>';
            var_dump($result);
        }
        return $result;
    }


    /**
     * 小费
     * @return string
     * @param $post 数组参数 CANCEL_TEST
     */
    public function payonlinefee($tipData){
        $AppID = (($this->isDebug) ? self::APPID : ($this->AppID));
        $AppKey = (($this->isDebug) ? self::APPKEY : ($this->AppKey));
        $OpenID = (($this->isDebug) ? self::OPENID : ($this->OpenID));
        $url = (($this->isDebug) ? self::BILL_URL_TEST : (self::BILL_URL)).'payonlinefee.ashx';
        $guid = str_replace('-', '', $this->guid());
        $parameter = [
            'order_code' => $tipData['order_code'],                     # 订单编号
            'origin_id' => $tipData['origin_id'],                       # 第三方订单编号
            'onlinefee' => $tipData['onlinefee'],                       # 支付小费金额，最低1元，只能整数（不支持小数）
            'openid' => $OpenID,
            'appid' => $AppID,
            'timestamp' => time(),
            'nonce_str' => strtolower($guid),
        ];
        ksort($parameter);
        $parameter['sign'] = $this->sign($parameter, $AppKey);
        $result = $this->request_post($url, $parameter);
        if (!empty($result)){
            $result = json_decode($result, true);
        }
        return $result;
    }

    /**
     * 订单信息
     * @return string
     * @param $post 数组参数 CANCEL_TEST
     */
    public function getorderdetail($tipData){
        $AppID = (($this->isDebug) ? self::APPID : ($this->AppID));
        $AppKey = (($this->isDebug) ? self::APPKEY : ($this->AppKey));
        $OpenID = (($this->isDebug) ? self::OPENID : ($this->OpenID));
        $url = (($this->isDebug) ? self::BILL_URL_TEST : (self::BILL_URL)).'getorderdetail.ashx';
        $guid = str_replace('-', '', $this->guid());
        $parameter = [
            'order_code' => $tipData,                                # 订单编号
            'openid' => $OpenID,
            'appid' => $AppID,
            'timestamp' => time(),
            'nonce_str' => strtolower($guid),
        ];
        ksort($parameter);
        $parameter['sign'] = $this->sign($parameter, $AppKey);
        $result = $this->request_post($url, $parameter);
        if (!empty($result)){
            $result = json_decode($result, true);
        }
        return $result;
    }



    /**
     * 发起http post请求
     */
    private function request_post($url, array $post_data){
        if (empty($url) || empty($post_data)) {
            return false;
        }
        $log = new Logging();
        $log->lfile('uu_express');
        $time = strtotime(date('Y-m-d H:i:s'));
        $log->lwrite('url: ' . $url);
        $log->lwrite($time.': ' . (json_encode($post_data,JSON_UNESCAPED_UNICODE)));

        $arr = [];
        foreach ($post_data as $key => $value) {
            $arr[] = $key . '=' . $value;
        }

        $curlPost = implode('&', $arr);
        $log->lwrite($time.'FORM-DATA: ' . (json_encode($post_data,JSON_UNESCAPED_UNICODE)));
        $postUrl = $url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postUrl);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);
        curl_close($ch);
        $log->lwrite($time . ',' . json_encode(json_decode($data, true), JSON_UNESCAPED_UNICODE));
        return $data;
    }

    /** 随机字符串
     * @return string
     */
    private function guid()
    {
        if (function_exists('com_create_guid')) {
            return com_create_guid();
        } else {
            mt_srand((double)microtime() * 10000);//optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = substr($charid, 0, 8) . $hyphen
                . substr($charid, 8, 4) . $hyphen
                . substr($charid, 12, 4) . $hyphen
                . substr($charid, 16, 4) . $hyphen
                . substr($charid, 20, 12);
            return $uuid;
        }
    }


    /** 生成签名
     * @param $data 字典排序数组
     * @param $appKey
     * @return string
     */
    private function sign($data, $appKey)
    {
        $arr = [];
        foreach ($data as $key => $value) {
            $arr[] = $key . '=' . $value;
        }

        $arr[] = 'key=' . $appKey;
        $str = strtoupper(implode('&', $arr));
        //$str = http_build_query($arr, '&');
//        var_dump('签名前:' . $str);
//        echo "<br />";die;
        return strtoupper(md5($str));
    }



}